import React, { useState } from 'react';
import { Card, Table, Tag, Button, Space, Modal, Form, Input, Radio, message, Select, DatePicker } from 'antd';
import type { TableProps } from 'antd';
import { EyeOutlined, CheckCircleOutlined, CloseCircleOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import './Review.scss';

interface OrderReviewType {
  key: string;
  orderNo: string;
  customerName: string;
  amount: number;
  products: string[];
  submitTime: string;
  urgency: 'high' | 'medium' | 'low';
  status: 'pending' | 'approved' | 'rejected';
  reason?: string;
}

const { RangePicker } = DatePicker;

// 模拟数据生成
const generateFakeReviews = (count: number): OrderReviewType[] => {
  const urgencyLevels: OrderReviewType['urgency'][] = ['high', 'medium', 'low'];
  const productList = ['iPhone 14', 'MacBook Pro', 'iPad Air', 'AirPods Pro', 'Apple Watch'];
  
  return Array.from({ length: count }, (_, index) => ({
    key: `${index + 1}`,
    orderNo: `REV${String(index + 1).padStart(6, '0')}`,
    customerName: `客户${index + 1}`,
    amount: Math.floor(Math.random() * 20000) + 5000,
    products: Array.from({ length: Math.floor(Math.random() * 3) + 1 }, () => 
      productList[Math.floor(Math.random() * productList.length)]
    ),
    submitTime: new Date(Date.now() - Math.floor(Math.random() * 7) * 24 * 60 * 60 * 1000).toLocaleString(),
    urgency: urgencyLevels[Math.floor(Math.random() * urgencyLevels.length)],
    status: 'pending'
  }));
};

const OrderReview: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<OrderReviewType[]>(() => generateFakeReviews(50));
  const [filteredData, setFilteredData] = useState<OrderReviewType[]>(data);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState<OrderReviewType | null>(null);
  const [loading, setLoading] = useState(false);

  const urgencyColors = {
    high: 'red',
    medium: 'orange',
    low: 'green'
  };

  const urgencyText = {
    high: '紧急',
    medium: '普通',
    low: '低优先级'
  };

  const handleReview = (record: OrderReviewType, initialStatus: 'approved' | 'rejected') => {
    setCurrentOrder(record);
    form.setFieldsValue({
      status: initialStatus,
      reason: ''
    });
    setModalVisible(true);
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setData(prevData => 
        prevData.map(item => 
          item.key === currentOrder?.key
            ? { ...item, status: values.status, reason: values.reason }
            : item
        )
      );

      message.success('审核完成');
      setModalVisible(false);
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async (values: any) => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      let filtered = [...data];

      if (values.orderNo) {
        filtered = filtered.filter(item => 
          item.orderNo.toLowerCase().includes(values.orderNo.toLowerCase())
        );
      }

      if (values.customerName) {
        filtered = filtered.filter(item =>
          item.customerName.includes(values.customerName)
        );
      }

      if (values.urgency) {
        filtered = filtered.filter(item => item.urgency === values.urgency);
      }

      if (values.status) {
        filtered = filtered.filter(item => item.status === values.status);
      }

      if (values.dateRange) {
        const [start, end] = values.dateRange;
        filtered = filtered.filter(item => {
          const submitTime = new Date(item.submitTime).getTime();
          return submitTime >= start.valueOf() && submitTime <= end.valueOf();
        });
      }

      setFilteredData(filtered);
      message.success('查询成功');
    } catch (error) {
      message.error('查询失败');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    form.resetFields();
    setFilteredData(data);
  };

  const columns: TableProps<OrderReviewType>['columns'] = [
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 120,
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 100,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '商品清单',
      dataIndex: 'products',
      key: 'products',
      width: 200,
      render: (products: string[]) => (
        <Space wrap>
          {products.map(product => (
            <Tag key={product} color="blue">{product}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '紧急程度',
      dataIndex: 'urgency',
      key: 'urgency',
      width: 100,
      render: (urgency: keyof typeof urgencyColors) => (
        <Tag color={urgencyColors[urgency]}>
          {urgencyText[urgency]}
        </Tag>
      ),
    },
    {
      title: '提交时间',
      dataIndex: 'submitTime',
      key: 'submitTime',
      width: 180,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusConfig = {
          pending: { color: 'gold', text: '待审核' },
          approved: { color: 'green', text: '已通过' },
          rejected: { color: 'red', text: '已拒绝' }
        };
        const config = statusConfig[status as keyof typeof statusConfig];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '审核意见',
      dataIndex: 'reason',
      key: 'reason',
      width: 200,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => message.info('查看详情')}
          >
            详情
          </Button>
          {record.status === 'pending' && (
            <>
              <Button
                type="link"
                icon={<CheckCircleOutlined />}
                onClick={() => handleReview(record, 'approved')}
                style={{ color: '#52c41a' }}
              >
                通过
              </Button>
              <Button
                type="link"
                danger
                icon={<CloseCircleOutlined />}
                onClick={() => handleReview(record, 'rejected')}
              >
                拒绝
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="order-review">
      <Card className="search-card">
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          className="search-form"
        >
          <Form.Item name="orderNo" label="订单编号">
            <Input placeholder="请输入订单编号" allowClear />
          </Form.Item>
          
          <Form.Item name="customerName" label="客户名称">
            <Input placeholder="请输入客户名称" allowClear />
          </Form.Item>
          
          <Form.Item name="urgency" label="紧急程度">
            <Select
              placeholder="请选择紧急程度"
              allowClear
              style={{ width: 120 }}
              options={[
                { value: 'high', label: '紧急' },
                { value: 'medium', label: '普通' },
                { value: 'low', label: '低优先级' },
              ]}
            />
          </Form.Item>

          <Form.Item name="status" label="审核状态">
            <Select
              placeholder="请选择状态"
              allowClear
              style={{ width: 120 }}
              options={[
                { value: 'pending', label: '待审核' },
                { value: 'approved', label: '已通过' },
                { value: 'rejected', label: '已拒绝' },
              ]}
            />
          </Form.Item>

          <Form.Item name="dateRange" label="提交时间">
            <RangePicker showTime />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />} loading={loading}>
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card title="订单审核" className="review-card">
        <Table
          columns={columns}
          dataSource={filteredData}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showQuickJumper: true,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
          scroll={{ x: 1500 }}
        />
      </Card>

      <Modal
        title="订单审核"
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="status"
            label="审核结果"
            rules={[{ required: true, message: '请选择审核结果' }]}
          >
            <Radio.Group>
              <Radio value="approved">通过</Radio>
              <Radio value="rejected">拒绝</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="reason"
            label="审核意见"
            rules={[{ required: true, message: '请输入审核意见' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入审核意见" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default OrderReview; 